<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents, VxeTableDataRow } from 'vxe-table'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'
import { type RequestIndex, useCouponStatisticIndex, useCouponStatisticTotal, useExportStatusStatistics } from '@fl/api/anjutong/coupon-statistics'
import { formatTime } from '@fl/utils'
import { useRouter } from 'vue-router'

// defineOptions({
//     // eslint-disable-next-line vue/component-definition-name-casing
//     name: 'data-analysis-coupon-statistics',
// })

// 带参跳转
const router = useRouter()
const route = useRoute()
const outType = route.query.type as string
const outProjectName = route.query.projectName as string
const outStartDate = route.query.startDate as string
const outEndDate = route.query.endDate as string

const tableRef = ref()
const mergeCells = ref<any>([])

// 搜索条件、分页参数
const initialState = {
    projectName: '',
    receiveTime: ['', ''],
    receiveStartTime: '',
    receiveEndTime: '',
    writeOffTime: ['', ''],
    writeOffStartTime: '',
    writeOffEndTime: '',
}
const state = ref<RequestIndex>(cloneDeep(initialState))
const searchConditions = ref<RequestIndex>(cloneDeep(initialState))

const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const initialPage = toRaw({ ...tablePage.value })

if(outType === 'receive') {
    state.value.receiveTime = [outStartDate + ' 00:00:00', outEndDate + ' 23:59:59']
    searchConditions.value.receiveTime = state.value.receiveTime
} else if(outType === 'writeOff') {
    state.value.writeOffTime = [outStartDate + ' 00:00:00' , outEndDate + ' 23:59:59']
    searchConditions.value.writeOffTime = state.value.writeOffTime
}
state.value.projectName = outProjectName
searchConditions.value.projectName = outProjectName

// 查询列表 coupontype 1优惠券，2折扣券
const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    projectName: searchConditions.value.projectName,
    receiveStartTime: searchConditions.value.receiveTime?.[0] ? formatTime(searchConditions.value?.receiveTime[0], 'yyyy-MM-dd 00:00:00') : null,
    receiveEndTime: searchConditions.value.receiveTime?.[1] ? formatTime(searchConditions.value?.receiveTime[1], 'yyyy-MM-dd 23:59:59') : null,
    writeOffStartTime: searchConditions.value.writeOffTime?.[0] ? formatTime(searchConditions.value?.writeOffTime[0], 'yyyy-MM-dd 00:00:00') : null,
    writeOffEndTime: searchConditions.value.writeOffTime?.[1] ? formatTime(searchConditions.value?.writeOffTime[1], 'yyyy-MM-dd 23:59:59') : null
}))
const { data, isLoading } = useCouponStatisticIndex(params)

// 导出
const exportParams = computed(() => ({
    projectName: searchConditions.value.projectName,
    receiveStartTime: searchConditions.value.receiveTime?.[0] ? formatTime(searchConditions.value?.receiveTime[0], 'yyyy-MM-dd 00:00:00') : null,
    receiveEndTime: searchConditions.value.receiveTime?.[1] ? formatTime(searchConditions.value?.receiveTime[1], 'yyyy-MM-dd 23:59:59') : null,
    writeOffStartTime: searchConditions.value.writeOffTime?.[0] ? formatTime(searchConditions.value?.writeOffTime[0], 'yyyy-MM-dd 00:00:00') : null,
    writeOffEndTime: searchConditions.value.writeOffTime?.[1] ? formatTime(searchConditions.value?.writeOffTime[1], 'yyyy-MM-dd 23:59:59') : null
}))
const { data: totalData } = useCouponStatisticTotal(exportParams) // 参数同导出
const { isPending, mutateAsync } = useExportStatusStatistics(exportParams)
console.log(2222)
const records = ref()
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records)
        tablePage.value.total = data.value.total!
        // 处理表单合并
        let num = 1
        const arr = records.value.reduce((pre, cur, index, arr) => {
            if(index >= 1) {
                if(cur.projectId === arr[index-1].projectId) {
                    num += 1
                } else {
                    pre.push(num)
                    num = 1
                }
            }
            if(index === arr.length - 1) {
                pre.push(num)
            }
            return pre
        }, [])
        // console.log('arr', arr)

        let num2 = 0
        mergeCells.value = arr.reduce((pre, cur, index, arr) => {
            if(index === 0) {
                // row：行索引 , col , rowspan：几条数据 , colspan固定1
                pre.push(
                    { row: 0, col: 1, rowspan: cur, colspan: 1 },
                    { row: 0, col: 4, rowspan: cur, colspan: 1 },
                    { row: 0, col: 6, rowspan: cur, colspan: 1 },
                    { row: 0, col: 8, rowspan: cur, colspan: 1 },
                    { row: 0, col: 10, rowspan: cur, colspan: 1 },
                )
            } else {
                num2 += arr[index - 1]
                pre.push(
                    { row: num2, col: 1, rowspan: cur, colspan: 1 },
                    { row: num2, col: 4, rowspan: cur, colspan: 1 },
                    { row: num2, col: 6, rowspan: cur, colspan: 1 },
                    { row: num2, col: 8, rowspan: cur, colspan: 1 },
                    { row: num2, col: 10, rowspan: cur, colspan: 1 },
                )
            }
            return pre
        }, [])

        // console.log('mergeCells.value', mergeCells.value)
    }
})

// 搜索
function submit() {
    searchConditions.value = cloneDeep(state.value)
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    tablePage.value = initialPage
}

// 导出
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}

function toProjectCouponDetails(sName: string) {
    router.push(`/data-analysis/housing-act-detail?projectName=${sName}`)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const columns: PlusColumn[] = [
    {
        label: '项目名称',
        prop: 'projectName',
        valueType: 'copy',
    },
    {
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '领取时间',
        prop: 'receiveTime',
        valueType: 'date-picker',
    },
    {
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '核销时间',
        prop: 'writeOffTime',
        valueType: 'date-picker',
    },
]
const gridOptions = reactive<VxeGridProps>({
    mergeCells: computed(() => {
        return mergeCells.value
    }),
    mergeFooterItems: [
        { row: 0, col: 0, rowspan: 1, colspan: 3 },
    ],
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'projectName', slots: { default: 'projectName' }, title: '项目名称', minWidth: 100 },
        { field: 'couponName', title: '优惠券名称', minWidth: 100 },
        { field: 'totalReceives', title: '领取人数' },
        { field: 'projectTotalReceives', title: '领取人数(合计)' }, // 项目总
        { field: 'totalQuantity', title: '领取数量' },
        { field: 'projectTotalQuantity', title: '领取数量（合计）' },
        { field: 'totalWriteOffs', title: '核销量' },
        { field: 'projectTotalWriteOffs', title: '核销量(合计)' },
        { field: 'contractCount', title: '意向签约数' },
        { field: 'projectTotalContractCount', title: '意向签约数(合计)' },
    ],
    showFooter: true,
    footerData: [
        {
            seq: '合计',
            // ownerCount: computed(() => ownerCountTotal.value),
            totalReceives: computed(() => totalData.value?.totalReceives),
            projectTotalReceives: computed(() => totalData.value?.projectTotalReceives),
            totalQuantity: computed(() => totalData.value?.totalQuantity),
            projectTotalQuantity: computed(() => totalData.value?.projectTotalQuantity),
            totalWriteOffs: computed(() => totalData.value?.totalWriteOffs),
            projectTotalWriteOffs: computed(() => totalData.value?.projectTotalWriteOffs),
            contractCount: computed(() => totalData.value?.contractCount),
            projectTotalContractCount: computed(() => totalData.value?.projectTotalContractCount),
        },
    ]
})
</script>

<template>
    <ElCard class="mb-20" shadow="never">
        <SearchForm v-model="state" :columns="columns" submit-text="搜索" @reset="reset" @submit="submit" />
    </ElCard>

    <ElCard shadow="never">
        <SearchTable ref="tableRef" v-bind="gridOptions" v-model:pager="tablePage" :loading="isLoading" :data="records"
            @page-change="handlePageChange">
            <template #projectName="{ row }">
                <span class="text-#da0004 cursor-pointer"
                      @click="toProjectCouponDetails(row.projectName)"
                >{{ row.projectName }}</span>
            </template>

            <template #toolbar_buttons>
                <ElButton type="primary" @click="exportData" :loading="isPending">
                    导出
                </ElButton>
            </template>
        </SearchTable>
    </ElCard>
</template>
